package com.xxkj.drugtraceability.ui.tracdetail

import android.text.Html
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.*
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.utils.showCompleteToast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.*

/**
 * author: zhoujingjin
 * created on: 2024/9/10 14:43
 * description:医嘱发药采集
 */
class TracDetailActivity:BaseVMActivity() {
    private val binding by binding<ActivityTracdetailBinding>(R.layout.activity_tracdetail)
    private val viewModel by viewModel<TracDetailViewModel>()
    private lateinit var adapter: TracDetailAdapter
    private var patientId:String?=""
    private var tradeType:String="1"
    private var dataType:String="1"
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            recyclerView.layoutManager = LinearLayoutManager(this@TracDetailActivity)
            adapter = TracDetailAdapter({
                viewModel.barcode = ""
                viewModel.lastIndex = viewModel.selectIndex.value?:-1
                viewModel.selectIndex.postValue(it)
            },{
                BlueDialog(this@TracDetailActivity,"您确定要修改追溯码么？"){
                    val list = mutableListOf<DrugTraceWithNum>()
                    it.drugTracInfoList?.forEach {drag->
                        if (!drag.drugTracCodg.isNullOrEmpty()){
                            list.add(DrugTraceWithNum(drag.drugTracCodg,drag.drugTracCodeNum))
                        }
                    }
                    viewModel.tracCodeModify(Gson().toJson(ModifyRequest(it.id,list,tradeType)))
                }

            },{
                BlueDialog(this@TracDetailActivity,"您确定要上传追溯码么？"){
                    viewModel.tracCodeUpload(Gson().toJson(TracCodeUploadRequest(dataType,it.id,tradeType)))
                }
            })
            tvCancel.clickN {
                YellowDialog(this@TracDetailActivity,resources.getString(R.string.cancel_all)){
                    //清空所有追溯码
                    finish()
                }
            }
            tvClear.clickN {
                YellowDialog(this@TracDetailActivity,resources.getString(R.string.clear_all)){
                    //清空所有追溯码
                    adapter.data.forEach {
                        it.drugTracInfoList?.clear()
                    }
                    adapter.notifyDataSetChanged()
                }
            }
            tvSave.clickN {
                var alert = false
                var noData = true
                adapter.data.forEach {
                    if (!it.drugTracInfoList.isNullOrEmpty()){
                        noData = false
                    }
                    if(it.drugTracInfoList?.size!=it.drugNum?.toDouble()
                        ?.toInt()){
                        alert = true
                    }
                }
                if (noData){
                    //提示没有任何数据
                    YellowDialog(this@TracDetailActivity,resources.getString(R.string.no_data),type = 1){

                    }
                }else{
                    if (alert){
                        BlueDialog(this@TracDetailActivity,resources.getString(R.string.scan_not_all)){
                            //保存数据
                          val filter =  viewModel.prescriptioninfo.filter {
                               val filter = it.drugInfoList.filter { drugInfoBean ->
                                    !drugInfoBean.drugTracInfoList.isNullOrEmpty()
                                }
                                filter.isNotEmpty()
                            }
                            viewModel.finishScanDrugCode(FinishAdviceRequest("2",filter,viewModel.Prescriptionbarcode))
                        }
                    }else{
                        //保存数据
                        viewModel.finishScanDrugCode(FinishAdviceRequest("2",viewModel.prescriptioninfo,viewModel.Prescriptionbarcode))
                    }
                }
            }
            recyclerView.adapter = adapter
        }
    }

    override fun initData() {
         tradeType = intent.getStringExtra("tradeType")
        dataType = intent.getStringExtra("dataType")?:"1"
        var isRollBackTrade = intent.getBooleanExtra("isRollBackTrade", false)
        adapter.setRollBackTrade(isRollBackTrade)
         val data = Gson().fromJson(intent.getStringExtra("data"),TwoItemData::class.java)
        patientId = data.preId
        binding.apply {
            tvContent.text = data.psnName
            val buffer = StringBuffer()
            buffer.append("<font color='#666666'>")
            buffer.append("门诊/住院号:")
            buffer.append("</font>")
            buffer.append("<font color='#33333F'>")
            buffer.append(data.rxno)
            buffer.append("</font>")
            tvDetail.text = Html.fromHtml(buffer.toString())

            val buffer1 = StringBuffer()
            buffer1.append("<font color='#666666'>")
            buffer1.append("上传日期:")
            buffer1.append("</font>")
            if (!data.prescriptionTime.isNullOrEmpty()) {
                buffer1.append("<font color='#494953'>")
                if (data.prescriptionTime.length > 10) {
                    buffer1.append(data.prescriptionTime.substring(0,10))
                } else {
                    buffer1.append(data.prescriptionTime)
                }
                buffer1.append("</font>")
            }
            tvDate.text = Html.fromHtml(buffer1.toString())
        }
        viewModel.tracCodedetail(patientId,tradeType)
    }

    override fun startObserve() {
        viewModel.baseUiModel.observe(this, Observer {
            if (it.showLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
            if (!it.showError.isNullOrEmpty()){
                BlueDialog(this,it.showError!!,type = 1){}
            }
            if (it.showSuccess==true){
                showCompleteToast(this)
                viewModel.tracCodedetail(patientId,tradeType)
            }
        })
        viewModel.uiState.observe(this, Observer {
            if (it.isLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
            if (!it.isError.isNullOrEmpty()){
                BlueDialog(this,it.isError!!,type = 1){}
            }
            if (it.isSuccess==true){
                showCompleteToast(this)
                viewModel.tracCodedetail(patientId,tradeType)
            }
        })
        viewModel.showList.observe(this, Observer { list->
            adapter.setList(list)
        })
        viewModel.selectIndex.observe(this, Observer {
            adapter.data.forEachIndexed { index, drugInfoBean ->
                drugInfoBean.isSelected = it == index
                if (viewModel.barcode.isNotEmpty()) {
                    drugInfoBean.drugTracInfoList?.forEach { drug ->
                        if (drug.drugTracCodg == viewModel.barcode) {
                            BlueDialog(this, "该追溯码已在列表中，无需重复扫码", type = 1) {}
                            return@Observer
                        }
                    }
                    if (it == index && drugInfoBean.drugTracInfoList?.size == drugInfoBean.drugNum?.toDouble()
                            ?.toInt()
                    ) {
                        BlueDialog(this, "该药品溯源码添加超过上限", type = 1) {}
                        return@Observer
                    }
                }
            }
            if (it!=-1){
                binding.recyclerView.scrollToPosition(it)
                adapter.data[it].isSelected = true
                if (viewModel.barcode.isNotEmpty()){
                    if(adapter.data[it].drugTracInfoList==null){
                        adapter.data[it].drugTracInfoList = mutableListOf()
                    }
                    var drugTracCodeNum = countDrugTracCodeNum(adapter.data[it])
                    adapter.data[it].drugTracInfoList!!.add(DrugTrace(drugTracCodg = viewModel.barcode,drugTracCodeNum = drugTracCodeNum))
                }
            }
            adapter.notifyDataSetChanged()
//            if (viewModel.lastIndex!=-1)
//            adapter.notifyItemChanged(viewModel.lastIndex)
        })

    }
    fun countDrugTracCodeNum(drugInfoBean: DrugInfoBean): Integer {
        if (drugInfoBean.trdnFlag != "1") return Integer(1)
        var maxNum = 1
        var scanNum = 0
        try {
            maxNum = drugInfoBean.drugNum!!.toDouble().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        drugInfoBean.drugTracInfoList?.forEach {
            try {
                scanNum += it.drugTracCodeNum!!.toInt()
            } catch (e: Exception) {
            }
        }
        var count = maxNum - scanNum
        if (count < 1) count = 1
        return Integer(count)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@TracDetailActivity)){
                        val barcodeMessage = this.any as BarcodeMessage
                        if(barcodeMessage.type== BarcodeType.SUYUAN){
                            if (viewModel.canAdd){
                                //扫码去
                                viewModel.trugTracCodgIsGather(barcodeMessage.barcode)
                            }
                        }else{
                            YellowDialog(this@TracDetailActivity,resources.getString(R.string.scan_suyuan),type = 1){}
                        }
                    }
                }
            }
        }
    }
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}